package com.modules.groups.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.response.ResponseVO;
import com.common.utils.R;
import com.modules.groups.entity.Groups;
import com.modules.groups.service.IGroupsService;
import com.modules.user.entity.UserEntity;
import com.modules.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/groups")
public class GroupsController {

    @Autowired
    private IGroupsService groupsService;

    @Autowired
    private IUserService userService;

    // 分组的分页列表
    @RequestMapping("/getPageList")
    public R getPageList(@RequestParam Map<String, Object> params){
        return groupsService.getPageList(params);
    }

    // 根据分组创建人id获取分组列表
    @GetMapping("/getList")
    public R getList(@RequestParam("createBy")Integer createBy){
        return R.ok().put("data", groupsService.list(new LambdaQueryWrapper<Groups>()
            .eq(Groups::getCreateBy, createBy)));
    }

    // 获得单个分组信息
    @GetMapping ("/getEntityById/{id}")
    public R getEntityById(@PathVariable Integer id){
        Groups groups = groupsService.getOne(new QueryWrapper<Groups>().lambda().eq(Groups::getId, id));
        return R.ok().put("data", groups);
    }

    // 添加/编辑分组
    @PostMapping("/saveEntity")
    public R saveEntity(@RequestHeader("token")String token, @RequestBody Groups groups){
        UserEntity userEntity = userService.getUserByLoginToken(token);
        if (groups.getId() == null){
            groups.setCreateBy(userEntity.getId());
            groups.setCreateTime(new Date());
        } else {
            groups.setUpdateTime(new Date());
        }
        groupsService.saveOrUpdate(groups);
        return R.ok();
    }

    // 删除分组
    @DeleteMapping("/removeEntity/{id}")
    public R removeEntity(@PathVariable Integer id){
        Groups groups = this.groupsService.getById(id);
        groupsService.removeById(groups);
        return R.ok();
    }
}
